/*
 * Copyright (c) 2016, FPX and/or its affiliates. All rights reserved.
 * Use, Copy is subject to authorized license.
 */
package com.fpx.open.platform.controller;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.stream.StreamSource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fpx.open.platform.common.util.DateUtil;
import com.fpx.open.platform.common.util.HTTPClient;
import com.fpx.open.platform.common.util.MD5Util;
import com.fpx.open.platform.domain.ae.response.Response;
import com.fpx.open.platform.domain.ae.response.Responses;
import com.fpx.open.platform.domain.vo.InvokeLogQuery;
import com.fpx.open.platform.service.SubjectiveOrderService;
import com.fpx.xms.api.base.model.InvokeLog;
import com.fpx.xms.api.base.model.Result;
import com.fpx.xms.api.base.util.CommonUtils;

/**
 * 
 * @author shiw
 * @date 2016年8月17日
 */
@Controller
@RequestMapping("order")
public class SubjectiveOrderController {

//	@Resource
//	SubjectiveOrderService subjectiveOrderService;
	
	private final Logger logger = LoggerFactory.getLogger(getClass());
	
	private static final Logger LOGGER = LoggerFactory.getLogger(SubjectiveOrderController.class);
	
	@Resource
    Jaxb2Marshaller jaxb2Marshaller;
	
	@RequestMapping("create")
	public String create(ModelMap modelMap){
		String orderCode = String.format("LU0%s", DateUtil.getCurrTime("MMddHHmmssSSS"));
		String mailNo = String.format("UC%sSG", DateUtil.getCurrTime("MMddHHmmssSSS"));
		String tradeId = DateUtil.getCurrTime("MMddHHmmss");
		String date = DateUtil.getCurrTime(DateUtil.DATE_FORMAT_S);
		String xml = "<logisticsEventsRequest><logisticsEvent><eventHeader><eventType>LOGISTICS_PACKAGE_SEND</eventType><eventTime>%s</eventTime><eventSource>taobao</eventSource><eventTarget>Tran_Store_11174375</eventTarget></eventHeader><eventBody><order><mailNo>none</mailNo><serviceItemId>5000000011398</serviceItemId><bizCode>AE_4PL_ONLINE</bizCode>"
				+ "<orderCode>%s</orderCode><tradeId>%s</tradeId><parcelInspect>0</parcelInspect><domesticExpressCode>Tran_Store_11174375</domesticExpressCode><domesticExpressId>5000000231144</domesticExpressId><domesticExpressName>递四方深圳仓-经济</domesticExpressName><categoryFeature>00</categoryFeature><sendContact><wangwangId>cn110318230</wangwangId><name>周宏宇</name><phone>13417478691</phone><mobile>13417478691</mobile><email>pandychow@gmail.com</email><country>中国</country><province>广东省</province><city>深圳市</city><streetAddress>民治水尾2区23栋904</streetAddress><areaId>440323</areaId><zipCode>518131</zipCode><district>龙华新区</district></sendContact><receiverContact><wangwangId>es1075209592</wangwangId><name>RAFAEL LARA PEREZ</name><phone/><mobile>630294395</mobile><email>ostraina@msn.com</email><country>ES</country><province>MALAGA</province><city>ANDALUCIA</city><streetAddress>C/ MARTIN DE LA PLAZA N 16-J</streetAddress><areaId>199</areaId><zipCode>29010</zipCode><district/></receiverContact><pickupContact><wangwangId>cn110318230</wangwangId><name>周宏宇</name><phone>13417478691</phone><mobile>13417478691</mobile><email>pandychow@gmail.com</email><country>中国</country><province>广东省</province><city>深圳市</city><streetAddress>民治水尾2区23栋904</streetAddress><areaId>440323</areaId><zipCode>518131</zipCode><district>龙华新区</district></pickupContact><doorPickup>1</doorPickup><subOrders><subOrder>"
				+ "<mailNo>%s</mailNo><zoneCode/><firstRoute>true</firstRoute><routerNum>1</routerNum><mailType>1</mailType><tradeId>%s</tradeId><uniqueCode>%s#%s#DISTRIBUTOR_11131497#1</uniqueCode><interCarrier>DISTRIBUTOR_11131497</interCarrier><orderCode>%s</orderCode><totalItemPrice>300</totalItemPrice><shipType>0</shipType><weight>40</weight><sendContact><wangwangId>cn110318230</wangwangId><name>Andy Chow</name><phone>13590192240</phone><mobile>13590192240</mobile><email/><country>中国</country><province>guang dong sheng</province><city>shen zhen shi</city><streetAddress>min zhi jie dao~~~Minzhi street</streetAddress><areaId>1</areaId><zipCode>518000</zipCode><district>bao an qu</district></sendContact><receiverContact><wangwangId>es1075209592</wangwangId><name>RAFAEL LARA PEREZ</name><phone/><mobile>630294395</mobile><email>ostraina@msn.com</email><country>ES</country><province>MALAGA</province><city>ANDALUCIA</city><streetAddress>C/ MARTIN DE LA PLAZA N 16-J</streetAddress><areaId>199</areaId><zipCode>29010</zipCode><district/></receiverContact><items><item><itemId>32539996021</itemId><itemName>Welding Fluxes</itemName><itemUrl>http://www.aliexpress.com/item//32539996021.html</itemUrl><itemCategoryName>Welding Fluxes</itemCategoryName><itemUnitPrice>300</itemUnitPrice><itemQuantity>1</itemQuantity><itemWeight>40</itemWeight><hasBattery>false</hasBattery><batteryInfo/><itemNameCN>焊剂</itemNameCN><itemCategoryNameCN>焊剂</itemCategoryNameCN></item></items><undeliveryOption>2</undeliveryOption><hasBattery>false</hasBattery></subOrder></subOrders><orderCreateTime>%s</orderCreateTime></order></eventBody></logisticsEvent></logisticsEventsRequest>";
		xml = String.format(xml, date, orderCode, tradeId, mailNo, tradeId, orderCode, mailNo, orderCode, date);
		try {
			xml = xml.replaceAll("&amp;", "|").replaceAll("&", "|");
			xml = CommonUtils.formatXml(xml);
		} catch (Exception e) {
			logger.error("", e);
		} 
		modelMap.addAttribute("xml", xml);
		return "/create-order";
	}
	
	@RequestMapping("last/create")
	public String lastCreate(ModelMap modelMap) {
		String orderCode = String.format("LU0%s", DateUtil.getCurrTime("MMddHHmmssSSS"));
		String mailNo = String.format("UC%sSG", DateUtil.getCurrTime("MMddHHmmssSSS"));
		String tradeId = DateUtil.getCurrTime("MMddHHmmss");
		String date = DateUtil.getCurrTime(DateUtil.DATE_FORMAT_S);
		String xml = "<logisticsEventsRequest><logisticsEvent><eventHeader><eventType>LOGISTICS_BATCH_SEND</eventType><eventTime>%s</eventTime><eventSource>taobao</eventSource><eventTarget>DISTRIBUTOR_11131497</eventTarget></eventHeader><eventBody><OrderInfos><product><productNameCN>手机屏保膜</productNameCN><productNameEN>S5 Screen Protectors</productNameEN><productQantity>3</productQantity><productCateCN>手机屏保膜</productCateCN><productCateEN>S5 Screen Protectors</productCateEN><productId>2033353400</productId><productCategory>Phones &amp; Telecommunications|Mobile Phone Accessories &amp; Parts|Screen Protectors</productCategory><producingArea/><productWeight>17</productWeight><productPrice>75</productPrice><extendFields>customCode=</extendFields><productURL>http://www.aliexpress.com/item//2033353400.html</productURL></product></OrderInfos><ecCompanyId>taobao</ecCompanyId><serviceItemId>5000000011398</serviceItemId><bizCode>AE_4PL_ONLINE</bizCode><whCode>Tran_Store_11174375</whCode><logisticsOrderId>52638819747</logisticsOrderId>"
				+ "<tradeId>%s</tradeId><mailNo>%s</mailNo><Rcountry>RU</Rcountry><Rprovince>Perm Krai</Rprovince><Rcity>Perm</Rcity><Remail>matang1ch@gmail.com</Remail><Raddress>Podlesnaya 7 59</Raddress><Rpostcode>614097</Rpostcode><Rname>Maltsev Dmitriy Olegovich</Rname><Rphone>79519419450</Rphone><Sname>ChenWeiJia</Sname><SwangwangId>cn1511537945</SwangwangId><Sprovince>Guangdong</Sprovince><Scity>Shenzhen</Scity><Saddress>HuaQiang North Road Futian District,Shenzhen,Guangdong,CN,518000</Saddress><Sphone>13751110926</Sphone><Spostcode>518000</Spostcode><SstoreName>Jia Lin communication</SstoreName><channel>HK</channel><Itotleweight>18</Itotleweight><Itotlevalue>75</Itotlevalue><totleweight>18</totleweight><country>CN</country><mailKind>1</mailKind><mailClass>L</mailClass><batchNo/><mailType>SUMAITONG</mailType><faceType>2</faceType><undeliveryOption>2</undeliveryOption><hasBattery>false</hasBattery><refunderContact><wangwangId>cn1511537945</wangwangId><name>ChenWeiJia</name><phone/><mobile>13751110926</mobile><email/><country>CN</country><province>Guangdong</province><city>Shenzhen</city><street>HuaQiang North Road Futian District,Shenzhen,Guangdong,CN,518000</street><zipCode>518000</zipCode><district/></refunderContact><pickUpAddress>中国广东省深圳市宝安区深圳市宝安国际机场广东省深圳市宝安区深圳国际机场 机场四道 国内航空货站201-221</pickUpAddress><packageCode>CN_PACKAGE_CODE_ABS</packageCode>"
				+ "<orderCode>%s</orderCode></eventBody></logisticsEvent></logisticsEventsRequest>";
		xml = String.format(xml, date, tradeId, mailNo, orderCode);
		try {
			xml = xml.replaceAll("&amp;", "|").replaceAll("&", "|");
			xml = CommonUtils.formatXml(xml);
		} catch (Exception e) {
			logger.error("", e);
		} 
		modelMap.addAttribute("xml", xml);
		return "/last-create-order";
	}
	
	@RequestMapping("hold")
	public String hold(ModelMap modelMap){
		String orderCode = String.format("LU0%s", DateUtil.getCurrTime("MMddHHmmssSSS"));
		String mailNo = String.format("UC%sSG", DateUtil.getCurrTime("MMddHHmmssSSS"));
		String tradeId = DateUtil.getCurrTime("MMddHHmmss");
		String date = DateUtil.getCurrTime(DateUtil.DATE_FORMAT_S);
		String xml = "<logisticsEventsRequest><logisticsEvent><eventHeader><eventType>LOGISTICS_PACKAGE_CANCEL</eventType><eventTime>%s</eventTime>"
				+ "<eventSource>taobao</eventSource><eventTarget>FPXSS</eventTarget></eventHeader><eventBody><order><mailNo>%s</mailNo><orderCode>%s</orderCode><tradeId>%s</tradeId></order></eventBody></logisticsEvent></logisticsEventsRequest>";
		xml = String.format(xml, date, mailNo, orderCode, tradeId);
		try {
			xml = xml.replaceAll("&amp;", "|").replaceAll("&", "|");
			xml = CommonUtils.formatXml(xml);
		} catch (Exception e) {
			logger.error("", e);
		} 
		modelMap.addAttribute("xml", xml);
		return "/hold";
	}
	
	
	@RequestMapping("save")
	@ResponseBody
	public Result save(String xml, HttpServletRequest request, String msg_type){
		if(StringUtils.isNotBlank(xml)){
			try {
				xml = xml.replaceAll("&amp;", "|").replaceAll("&", "|");
				xml = CommonUtils.formatXml2(xml);
			} catch (Exception e) { }
		}
		Map<String, String> paraMaps = new HashMap<String, String>();
        paraMaps.put("logistics_interface", xml);
        paraMaps.put("msg_type", msg_type);
        paraMaps.put("data_digest", MD5Util.Md5Base64(xml + "DFKLJDSHJ253SD2"));
        String basePath = CommonUtils.getBasePath(request);
        String strResult;
        Responses responses = null;
		try {
			strResult = HTTPClient.sendPostRequest(basePath + "ae/receive", paraMaps);
			responses = (Responses) this.jaxb2Marshaller.unmarshal(new StreamSource(new StringReader(strResult)));
			if(responses.isHandlerSuccess()){
				return new Result("保存成功");
			}
			Response response = responses.getResponseItems().getResponse();
			return Result.error("保存失败：" + response.getReason() + " | " + response.getRemark());
		} catch (Exception e) {
			logger.error("", e);
			return Result.error(e.getMessage());
		}
	}
	
	@RequestMapping("log")
	public String queryLog(ModelMap modelMap, InvokeLogQuery invokeLogQuery){
//		if(invokeLogQuery != null && invokeLogQuery.getOrderNo() != null){
//			List<InvokeLog> invokeLogList = this.subjectiveOrderService.queryInvokeLog(invokeLogQuery);
//			modelMap.addAttribute("invokeLogList", invokeLogList);
//		}
		return "/newlog";
	}
	

	@RequestMapping("log/detail")
	public String queryLogDetail(Long id, ModelMap modelMap){
//		if(id != null){
//			InvokeLog invokeLog = this.subjectiveOrderService.queryInvokeLog(id);
//			modelMap.addAttribute("invokeLog", invokeLog);
//		}
		return "/log-detail";
	}
	
	
	@RequestMapping("/getdata")
	@ResponseBody
	public Object queryLogDetail(){ 
		Map<String,String> data = new HashMap<String,String>();
		List<Map<String,String>> ret = new ArrayList<Map<String,String>>();
		data.put("id", "11");
		data.put("cn", "test1");
		data.put("cc", "test2");
		data.put("ct", "test3");
		data.put("ca", "test4");
		data.put("ck", "test5");
		ret.add(data);
		Map obj = new HashMap();
		obj.put("data", ret);
		obj.put("recordsTotal", 1);
		obj.put("recordsFiltered", 1);
		return obj;
	}
	 
}
